
"""
@author: 
@file: pretty.py
@time: 2023/12/12 11:10
@desc: 
"""
from django.shortcuts import render, redirect
from app01 import models
from app01.utils.pagination import Pagination
from app01.utils.form import PrettyModelForm, PrettyEditModelForm


# 靓号管理
def pretty_list(request):
    """ 靓号列表 """

    data_dict = {}
    search_data = request.GET.get('q', "")
    if search_data:
        data_dict["mobile__contains"] = search_data

    queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")

    page_object = Pagination(request, queryset)
    context = {
        "queryset": page_object.page_queryset,
        "search_data": search_data,
        "page_string": page_object.html(),
    }

    return render(request, 'pretty_list.html', context)


def pretty_add(request):
    """ 靓号添加 """
    if request.method == "GET":
        form = PrettyModelForm()
        return render(request, 'pretty_add.html', {'form': form})

    # 用户POST提交数据
    form = PrettyModelForm(data=request.POST)
    if form.is_valid():
        # 如果数据合法,保存到数据库
        form.save()
        return redirect('/pretty/list/')

    # 校验失败(在页面上显示错误信息)
    return render(request, 'pretty_add.html', {"form": form})


def pretty_edit(request, nid):
    """ 编辑靓号 """
    """ 编辑用户 """
    row_object = models.PrettyNum.objects.filter(id=nid).first()

    if request.method == "GET":
        # 根据ID获取编辑的用户数据(对象)

        form = PrettyEditModelForm(instance=row_object)
        return render(request, 'user_edit.html', {'form': form})

    form = PrettyEditModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')

    return render(request, 'pretty_edit.html', {"form": form})


def pretty_delete(request, nid):
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect('/pretty/list/')